package cn.kgc.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.api.entity.Depts;
import cn.kgc.api.entity.Users;
import cn.kgc.api.form.DeptsAddForm;
import cn.kgc.api.form.DeptsUpdateForm;
import cn.kgc.api.service.DeptsService;
import cn.kgc.api.service.UsersService;
import cn.kgc.common.constant.ResultConstant;
import cn.kgc.common.util.HttpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kgc
 */
@RestController
@RequestMapping("/depts")
@Api(tags = "部门模块")
@Validated
@Slf4j
@CrossOrigin
public class DeptsController {
    /**
     * 注入业务层
     */
    @Resource
    private DeptsService deptsService;

    @Resource
    private UsersService usersService;

    /**
     * 查询所有数据
     *
     * @return 所有数据
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询所有数据")
    @CrossOrigin
    public List<Depts> selectAll() {
        return deptsService.list();
    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "根据id查询数据")
    public Depts detail(@PathVariable int id) {
        return deptsService.getById(id);
    }

    @PostMapping("/list2")
    @ApiOperation(value = "根据条件查询数据")
    public List<Depts> selectByDeptName(@RequestBody Map<String, String> params) {
        LambdaQueryWrapper<Depts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(params.get("deptName")
        ), Depts::getDeptName, params.get("deptName"));

        return deptsService.list(wrapper);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据id删除数据")
    public boolean deleteById(@PathVariable(value = "id") int id) {
        // 判断部门下有员工不能删除
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getDeptId, id);

        if (usersService.count(wrapper) > 0) {
            throw new HttpException(ResultConstant.DELETE_DEPT_ERROR);
        }
        //如果没有就可以删除
        return deptsService.removeById(id);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增部门信息")
    public boolean save(@RequestBody DeptsAddForm addForm) {
        //1 判断用户id在当前部门中是否存在
        Integer userId = addForm.getUserId();

        Users users = null;
        if (userId != 0) {
            users = usersService.getById(userId); //根据用户id查询用户信息
            if (users == null) {
                throw new HttpException(ResultConstant.USER_NOT_EXIST);
            }
        }


        //2 判断部门名称是否重复
        LambdaQueryWrapper<Depts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Depts::getDeptName, addForm.getDeptName());
        if (deptsService.count(wrapper) > 0) {
            throw new HttpException(ResultConstant.DEPT_REPEAT_ERROR);
        }


        //2 新增部门
        Depts depts = new Depts();

        depts.setDeptName(addForm.getDeptName());

        depts.setUserId(userId+"");

        if (users != null) {
            depts.setUserEmail(users.getUserEmail());

            depts.setUserName(users.getUserName());
        }

        return deptsService.save(depts);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改部门")
    public boolean update(@RequestBody DeptsUpdateForm updateForm) {
        //获取修改部门表单中的用户Id
        Integer userId = updateForm.getUserId();
        Users users = null;
        //如果用户Id不为0，则根据用户Id查询用户信息
        if (userId != 0) {
            users = usersService.getById(userId);
            //如果用户信息不存在，则抛出异常
            if (users == null) {
                throw new HttpException(ResultConstant.USER_NOT_EXIST);
            }
        }
        //根据部门的Id查询部门原来的信息
        Depts depts = deptsService.getById(updateForm.getId());
        //将修改部门表单中的信息复制到部门信息中
        BeanUtil.copyProperties(updateForm,depts);
        //更新时传入部门的负责人 部门中修改部门的负责人
        if (users != null) {
            depts.setUserEmail(users.getUserEmail());
            depts.setUserName(users.getUserName());
        }else {// 如果没有传入负责人 则将部门中的负责人信息为空
            depts.setUserName("");
            depts.setUserEmail("");
        }

        //更新部门信息
        return deptsService.updateById(depts);
    }
}